package com.bnz.servlet;

import com.alibaba.fastjson.JSON;
import com.bnz.entity.Classes;
import com.bnz.entity.Student;
import com.bnz.service.ClassesService;
import com.bnz.service.StudentService;
import com.bnz.util.PageResult;
import com.bnz.util.R;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/classes")
public class ClassesServlet extends HttpServlet {
    // 引入ClassesService
    private ClassesService classesService;

    // 重写初始化方法(程序一执行,就先执行这里的命令)
    @Override
    public void init() throws ServletException {
        // 1、拿到spring容器
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        // 2、得到容器中的bean,并赋值给studentService
        classesService = wac.getBean(ClassesService.class);

    }


    // 重写service方法
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1、处理中文乱码问题
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        // 2、获取请求参数(前端路径中带有的参数cmd=...)
        String cmd = req.getParameter("cmd");
        // 3、根据获取到的cmd的值,进行不同的操作,前提是不为空
        if (!StringUtils.isEmpty(cmd)) { // 得到的cmd不为空
            // 3.1、cmd=list,查询全部数据
            if ("list".equals(cmd)) {
                list(req, resp);
            }
        }
    }

    // 1、查询全部班级
    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 1.1、创建findAll()方法,查询所有数据
        List<Classes> list = classesService.findALL();
        // 1.2、利用统一返回工具类,统一传输值给前端
        R r = R.ok().data("list", list);
        // 1.3、讲查询到的数据,转换为json串,并输出到网页
        resp.getWriter().println(JSON.toJSONString(r));
        // 1.4、进行刷新
        resp.getWriter().flush();
    }

}
